package cn.danger.com.fragment.schedule;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.feezu.liuli.timeselector.TimeSelector;

import java.util.Date;
import java.util.Map;

import cn.bmob.v3.datatype.BmobDate;
import cn.danger.com.activity.CommonActivity;
import cn.danger.com.activity.R;
import cn.danger.com.fragment.BackHandledFragment;
import cn.danger.com.model.entity.Schedule;
import cn.danger.com.presenter.SchedulePresenter;
import cn.danger.com.presenter.SchedulePresenterImpl;
import cn.danger.com.util.Constants;
import cn.danger.com.util.FileCacheService;
import cn.danger.com.view.CommonView;
import cn.danger.com.widget.MyRelativeLayout;

/**
 * Created by 俊 on 2017/1/3.
 */
public class AddScheduleFragment extends BackHandledFragment implements View.OnClickListener, CommonView {

    private boolean hadIntercept;
    private View view;
    private CommonActivity activity;
    private Toolbar toolbar;
    private TextView toolbar_title;
    private EditText content_editText;
    private RelativeLayout date_start_layout;
    private TextView date_start_textView;
    private SwitchCompat remind_switch;
    private MyRelativeLayout remind_time_layout;
    private TextView remind_time;
    private EditText remind_time_textView;
    private MyRelativeLayout remind_ring_layout;
    private TextView remind_ring;
    private EditText remind_ring_textView;
    private MyRelativeLayout type_layout;
    private EditText type_textView;
    private long start_date = System.currentTimeMillis() + 60000;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            switch (msg.what) {
                case 1:
                    final String time = msg.obj.toString();
                    remind_time_textView.post(new Runnable() {
                        @Override
                        public void run() {
                            remind_time_textView.setText(time);
                        }
                    });
                    break;
                case 2:
                    final String ring = msg.obj.toString();
                    remind_ring_textView.post(new Runnable() {
                        @Override
                        public void run() {
                            remind_ring_textView.setText(ring);
                        }
                    });
                    break;
                case 3:
                    final String type = msg.obj.toString();
                    type_textView.post(new Runnable() {
                        @Override
                        public void run() {
                            type_textView.setText(type);
                        }
                    });
                    break;
                default:
                    break;
            }
        }
    };
    private ProgressDialog dialog;
    private SchedulePresenter presenter;
    private Bundle bundle;
    private Schedule schedule;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_add_schedule, container, false);

        bindView();
        bindEvent();

        return view;
    }

    @Override
    public void bindView() {
        activity = (CommonActivity) getActivity();
        toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        toolbar.setTitle("");
        activity.setSupportActionBar(toolbar);
        toolbar_title = (TextView) view.findViewById(R.id.toolbar_title);

        content_editText = (EditText) view.findViewById(R.id.content_editText);
        date_start_layout = (RelativeLayout) view.findViewById(R.id.date_start_layout);
        date_start_textView = (TextView) view.findViewById(R.id.date_start_textView);
        remind_switch = (SwitchCompat) view.findViewById(R.id.remind_switch);
        remind_time_layout = (MyRelativeLayout) view.findViewById(R.id.remind_time_layout);
        remind_time = (TextView) view.findViewById(R.id.remind_time);
        remind_time_textView = (EditText) view.findViewById(R.id.remind_time_textView);
        remind_ring_layout = (MyRelativeLayout) view.findViewById(R.id.remind_ring_layout);
        remind_ring = (TextView) view.findViewById(R.id.remind_ring);
        remind_ring_textView = (EditText) view.findViewById(R.id.remind_ring_textView);
        type_layout = (MyRelativeLayout) view.findViewById(R.id.type_layout);
        type_textView = (EditText) view.findViewById(R.id.type_textView);

        remind_switch.setChecked(true);

        dialog = new ProgressDialog(activity, ProgressDialog.THEME_HOLO_LIGHT);
        dialog.setMessage("正在执行...");
        dialog.setCanceledOnTouchOutside(false);

        presenter = new SchedulePresenterImpl(activity, this);

        bundle = getArguments();

        if (bundle != null) {
            schedule = (Schedule) bundle.getSerializable("schedule");
            if (schedule != null) {
                toolbar_title.setText(getResources().getString(R.string.update_schedule));
                content_editText.setText(schedule.getContent());
                start_date = Long.parseLong(schedule.getDate_start());
                if (schedule.getRemind() == 1) {
                    remind_switch.setChecked(true);
                } else {
                    remind_switch.setChecked(false);
                }
                remind_time_textView.setText(schedule.getRemind_time());
                remind_ring_textView.setText(schedule.getRemind_ring());
                type_textView.setText(schedule.getType());
                Log.i("danger", "objectId---->>>" + schedule.getObjectId());
            }
        }

        String start_time = new BmobDate(new Date(start_date)).getDate();
        String[] a = start_time.substring(0, start_time.length() - 3).split(" ");
        date_start_textView.setText(a[0] + "    " + a[1]);
    }

    @Override
    public void bindEvent() {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.finish();
            }
        });
        date_start_layout.setOnClickListener(this);
        remind_time_layout.setOnClickListener(this);
        remind_ring_layout.setOnClickListener(this);
        type_layout.setOnClickListener(this);
        remind_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    remind_time_layout.setEnabled(true);
                    remind_time_textView.setTextColor(getResources().getColor(R.color.font_color));
                    remind_time.setTextColor(getResources().getColor(R.color.font_color));
                    remind_ring_layout.setEnabled(true);
                    remind_ring_textView.setTextColor(getResources().getColor(R.color.font_color));
                    remind_ring.setTextColor(getResources().getColor(R.color.font_color));
                } else {
                    remind_time_layout.setEnabled(false);
                    remind_time_layout.setBackground(getResources().getDrawable(R.drawable.item_selector));
                    remind_time_textView.setTextColor(getResources().getColor(R.color.user_info_color));
                    remind_time.setTextColor(getResources().getColor(R.color.user_info_color));
                    remind_ring_layout.setEnabled(false);
                    remind_ring_layout.setBackground(getResources().getDrawable(R.drawable.item_selector));
                    remind_ring_textView.setTextColor(getResources().getColor(R.color.user_info_color));
                    remind_ring.setTextColor(getResources().getColor(R.color.user_info_color));
                }
            }
        });
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.modify_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.save) {
            if (bundle != null) {
                Log.i("danger", "update");
                updateSchedule();
            } else {
                Log.i("danger", "save");
                saveSchedule();
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.date_start_layout:
                chooseStartDate();
                break;
            case R.id.remind_time_layout:
                RemindTimeFragment remindTimeFragment = new RemindTimeFragment();
                remindTimeFragment.setHandler(handler);
                Bundle remind_time_bundle = new Bundle();
                remind_time_bundle.putString("index", remind_time_textView.getText().toString());
                remindTimeFragment.setArguments(remind_time_bundle);
                getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.container, remindTimeFragment).commit();
                break;
            case R.id.remind_ring_layout:
                RemindRingFragment remindRingFragment = new RemindRingFragment();
                remindRingFragment.setHandler(handler);
                Bundle remind_ring_bundle = new Bundle();
                remind_ring_bundle.putString("index", remind_ring_textView.getText().toString());
                remindRingFragment.setArguments(remind_ring_bundle);
                getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.container, remindRingFragment).commit();
                break;
            case R.id.type_layout:
                TypeFragment typeFragment = new TypeFragment();
                typeFragment.setHandler(handler);
                Bundle type_bundle = new Bundle();
                type_bundle.putString("index", type_textView.getText().toString());
                typeFragment.setArguments(type_bundle);
                getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.container, typeFragment).commit();
                break;
            default:
                break;
        }
    }

    private void chooseStartDate() {
        String time = new BmobDate(new Date(System.currentTimeMillis())).getDate();
        TimeSelector timeSelector = new TimeSelector(activity, new TimeSelector.ResultHandler() {
            @Override
            public void handle(String time) {
                String[] s = time.split(" ");
                date_start_textView.setText(s[0] + "    " + s[1]);
                try {
                    start_date = cn.danger.com.util.DateUtil.stringToLong(time + ":00", "yyyy-MM-dd HH:mm:ss");
                } catch (Exception e) {
                    showMessage("选取日期错误");
                }
            }
        }, time.substring(0, time.length() - 3), "2050-12-01 09:00");
        timeSelector.setMode(TimeSelector.MODE.YMDHM);
        timeSelector.show();
    }

    @Override
    public void showDialog() {
        dialog.show();
    }

    @Override
    public void hideDialog() {
        dialog.dismiss();
    }

    @Override
    public void showMessage(String message) {
        Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
        Intent intent = new Intent("update_schedule_list");
        if (message.equals(Constants.SUCCESS_TO_ADD_SCHEDULE) || message.equals(Constants.SUCCESS_TO_SAVE_LOCAL)) {
            activity.sendBroadcast(intent);
            if (bundle != null) {
                getFragmentManager().popBackStack();
            } else {
                activity.finish();
            }
        }
        if (message.equals(Constants.SUCCESS_TO_UPDATE_LOCAL) || message.equals(Constants.SUCCESS_TO_UPDATE_SCHEDULE)) {
            activity.sendBroadcast(intent);
            activity.finish();
        }
    }

    private void updateSchedule() {
        schedule.setContent(content_editText.getText().toString());
        schedule.setDate_start(start_date + "");
        if (remind_switch.isChecked()) {
            schedule.setRemind(1);
            schedule.setRemind_time(remind_time_textView.getText().toString());
            schedule.setRemind_ring(remind_ring_textView.getText().toString());
        } else {
            schedule.setRemind(2);
            schedule.setRemind_time("准时");
            schedule.setRemind_ring("苹果line");
        }
        schedule.setType(type_textView.getText().toString());
        FileCacheService service = new FileCacheService(activity);
        Map<String, String> map = (Map<String, String>) service.getSharePreference("userInfo");
        if (map.get("phone") == null) {
            schedule.setUsername("default");
        } else {
            schedule.setUsername(map.get("phone"));
        }
        presenter.updateSchedule(schedule);
    }

    private void saveSchedule() {
        Schedule new_schedule = new Schedule();
        new_schedule.setContent(content_editText.getText().toString());
        new_schedule.setDate_start(start_date + "");
        if (remind_switch.isChecked()) {
            new_schedule.setRemind(1);
            new_schedule.setRemind_time(remind_time_textView.getText().toString());
            new_schedule.setRemind_ring(remind_ring_textView.getText().toString());
        } else {
            new_schedule.setRemind(2);
            new_schedule.setRemind_time("准时");
            new_schedule.setRemind_ring("苹果line");
        }
        new_schedule.setType(type_textView.getText().toString());
        FileCacheService service = new FileCacheService(activity);
        Map<String, String> map = (Map<String, String>) service.getSharePreference("userInfo");
        if (map.get("phone") == null) {
            new_schedule.setUsername("default");
        } else {
            new_schedule.setUsername(map.get("phone"));
        }
        presenter.addSchedule(new_schedule);
    }

    @Override
    public boolean onBackPressed() {
        if (hadIntercept) {
            return false;
        } else {
            hadIntercept = true;
            return true;
        }
    }

}
